package com.fits.auth.api.controller;

import com.fits.framework.core.asserts.FitsAssertUtil;
import com.fits.framework.core.exception.BaseException;
import com.fits.framework.core.response.Result;
import com.fits.starter.api.controller.BaseController;
import com.fits.starter.common.security.Oauth2TokenDTO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import java.security.KeyPair;
import java.security.Principal;
import java.util.Map;

@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/oauth")
public class AuthController implements BaseController {
    @Autowired
    private TokenEndpoint tokenEndpoint;
    @Autowired
    private KeyPair keyPair;

    @PostMapping(value = "/token")
    public Result<Oauth2TokenDTO> postAccessToken(Principal principal, @RequestParam
    Map<String, String> parameters) {
        //获取token,内部调用UsernamePasswordAuthenticationToken校验账号密码
        OAuth2AccessToken accessToken = null;
        try {
            accessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        } catch (HttpRequestMethodNotSupportedException e) {
            throw new RuntimeException(e);
        }
        return ok(Oauth2TokenDTO.builder()
                .token(accessToken.getValue())
                .refreshToken(accessToken.getRefreshToken().getValue())
                .expiresIn(accessToken.getExpiresIn())
                .tokenHead("Bearer ")
                .build());
    }

    @GetMapping("/token/valid")
    public Result<Boolean> checkToken(@RequestParam String token) {
        FitsAssertUtil.beEmpty(token).throwException("token不能为空");
        String realToken = token.replace("Bearer ", "");
        try {
            Jwts.parser().setSigningKey(keyPair.getPublic())
                    .parseClaimsJws(realToken)
                    .getBody();
            return ok(true);
        } catch (ExpiredJwtException e1) {
            log.error("JWT已过期:{}", token);
        } catch (Exception e) {
            log.error("JWT格式验证失败:{}", token);
        }
        return ok(false);
    }
}
